package org.aman.publish.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.*;

/**
 * @author DaiJG
 * @Date created at 2018/11/22 15:48
 * @Description
 */
public class CmdUtil {
    public static boolean deleteDir(File dir){
        if(!dir.exists()){ 
            return true;
        }
        try {
            FileUtils.deleteDirectory(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return !dir.exists();
    }
    
    public static String execute(String command) {
        List<String> result = new Vector<>();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec(command);
            
            new CmdRespThread(p.getInputStream(), CmdRespThread.INFO, result).start();
            new CmdRespThread(p.getErrorStream(), CmdRespThread.ERROR, result).start();
            
            if (p.waitFor() != 0) {
                if (p.exitValue() == 1){ //p.exitValue()==0表示正常结束，1：非正常结束
                    System.err.println("["+command+"]命令执行失败!");
                }
            }
            return StringUtils.join(result, "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

}
